import 'dart:async';

import 'package:beamer/beamer.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:rabbit_mobile/service/home.api.dart';

class SMSVerificationCode extends StatefulWidget {
  final String phoneNumber;
  const SMSVerificationCode({
    super.key,
    required this.phoneNumber,
  });

  @override
  State<SMSVerificationCode> createState() => _SMSVerificationCodeState();
}

class _SMSVerificationCodeState extends State<SMSVerificationCode> {
  /// 輸入框控制器
  late TextEditingController? _textEditingController;

  /// 焦點控制器
  late FocusNode? _focusNode;

  /// 倒計時時常
  ValueNotifier<int> _countDownTimeNotifier = ValueNotifier<int>(0);

  /// 定時器
  late Timer _timer;

  @override
  void initState() {
    super.initState();
    _textEditingController = TextEditingController();
    _focusNode = FocusNode();
  }

  @override
  void dispose() {
    super.dispose();
    _textEditingController!.dispose();
    _focusNode!.dispose();
    _timer.cancel();
  }

  // 獲取驗證碼事件處理函數
  void _handleVerification() async {
    setState(() {
      _countDownTimeNotifier.value = 60;
    });
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      setState(() {
        _countDownTimeNotifier.value--;
        if (_countDownTimeNotifier.value <= 0) {
          _timer.cancel();
        }
      });
    });
    await GetSMSVerificationCode.getSMSVerificationCodeFetch(widget.phoneNumber, 'register');
    setState(() {
      _textEditingController!.clear();
    });
  }

  // 驗證手機驗證碼
  void _checkSMSVerificationCode() async {
    if (_textEditingController!.text.isEmpty) {
      EasyLoading.showError('驗證碼不能爲空');
      return;
    }
    RegExp smscodeRegExp = RegExp(r'^\d{6}$');
    bool isMatchSmsCode = smscodeRegExp.hasMatch(_textEditingController!.text);
    if (!isMatchSmsCode) {
      EasyLoading.showError('格式錯誤');
      return;
    }
    await CheckSMSVerificationCode.checkSMSVerificationCodeFetch(widget.phoneNumber, _textEditingController!.text);
    setState(() {
      _countDownTimeNotifier.value = 60;
    });
    Beamer.of(context).beamToNamed('/registerin/${widget.phoneNumber}/${_textEditingController!.text}');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: const Color(0xFF00CEA8),
        title: const Text(
          "用戶注冊",
          style: TextStyle(
            fontSize: 14,
            color: Color.fromARGB(255, 255, 255, 255),
          ),
        ),
        leading: IconButton(
          onPressed: () {
            Beamer.of(context).beamBack();
          },
          icon: Image.asset('assets/fanhui_light.png'),
        ),
      ),
      body: GestureDetector(
        onTap: () {
          _focusNode!.unfocus();
        },
        child: SingleChildScrollView(
          child: Column(
            children: [
              const Padding(
                padding: EdgeInsets.symmetric(vertical: 48),
                child: Align(
                  alignment: Alignment.center,
                  child: Text(
                    "請輸入接收到的驗證碼",
                    style: TextStyle(fontSize: 16, color: Colors.black),
                  ),
                ),
              ),
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 24),
                child: Container(
                  width: double.infinity,
                  height: 48,
                  decoration: const BoxDecoration(border: Border(bottom: BorderSide(width: 1, color: Colors.grey))),
                  child: Row(
                    children: [
                      const Padding(
                        padding: EdgeInsets.only(right: 12),
                        child: Text(
                          "請輸入驗證碼",
                          style: TextStyle(fontSize: 14, color: Colors.black),
                        ),
                      ),
                      Expanded(
                        child: TextField(
                          controller: _textEditingController,
                          focusNode: _focusNode,
                          decoration: InputDecoration(
                            border: InputBorder.none,
                            hintText: "請輸入驗證碼",
                            hintStyle: const TextStyle(
                              fontSize: 14,
                              color: Colors.grey,
                            ),
                            suffixIcon: _textEditingController!.text.isNotEmpty
                                ? IconButton(
                                    hoverColor: Colors.transparent,
                                    focusColor: Colors.transparent,
                                    splashColor: Colors.transparent,
                                    highlightColor: Colors.transparent,
                                    icon: const Icon(Icons.close),
                                    onPressed: () {
                                      _textEditingController!.clear();
                                    },
                                  )
                                : null,
                          ),
                          cursorColor: const Color(0xFF00CE8A),
                          style: const TextStyle(fontSize: 18, color: Colors.black),
                          keyboardType: TextInputType.number,
                          onChanged: (_) => setState(() {}),
                        ),
                      ),
                      GestureDetector(
                        onTap: _countDownTimeNotifier.value <= 0 ? _handleVerification : null,
                        child: Text(
                          _countDownTimeNotifier.value <= 0 ? "發送驗證碼" : "重新發送(${_countDownTimeNotifier.value})",
                          style: const TextStyle(fontSize: 14, color: Colors.black),
                        ),
                      )
                    ],
                  ),
                ),
              ),
              Padding(
                padding: const EdgeInsets.only(top: 32, bottom: 12),
                child: TextButton(
                  style: ButtonStyle(
                    overlayColor: WidgetStateProperty.all(Colors.transparent), // 移除水波纹效果
                  ),
                  onPressed: _checkSMSVerificationCode,
                  child: Container(
                    alignment: Alignment.center,
                    width: double.infinity,
                    height: 50,
                    decoration: const BoxDecoration(
                        color: Color(0xFF00CEA8), borderRadius: BorderRadius.all(Radius.circular(10))),
                    child: const Text(
                      "下一步",
                      style: TextStyle(
                        fontSize: 16,
                        color: Colors.white,
                      ),
                    ),
                  ),
                ),
              ),
              const Padding(
                padding: EdgeInsets.symmetric(horizontal: 12),
                child: Align(
                  alignment: Alignment.centerRight,
                  child: Text(
                    "需要幫助",
                    style: TextStyle(fontSize: 16, color: Color(0xFF00CEA8)),
                  ),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}
